package com.ljd.hosp.service.impl;

import com.alibaba.fastjson.JSON;
import com.ljd.hosp.repository.ScheduleRepository;
import com.ljd.hosp.service.ScheduleService;
import com.ljd.yygh.exception.YyghException;
import com.ljd.yygh.model.hosp.Schedule;
import com.ljd.yygh.result.ResultCodeEnum;
import com.ljd.yygh.vo.hosp.ScheduleQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Autowired
    ScheduleRepository scheduleRepository;

    @Override
    public void saveSchedule(Map<String, Object> paramMap) {
        String string = JSON.toJSONString(paramMap);
        Schedule schedule = JSON.parseObject(string, Schedule.class);
        String hoscode = schedule.getHoscode();
        String hosScheduleId = schedule.getHosScheduleId();
        Schedule sc = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode,hosScheduleId);
        if(null==sc) {
            schedule.setCreateTime(new Date());
        }
        schedule.setUpdateTime(new Date());
        schedule.setIsDeleted(0);
        schedule.setStatus(1);
        scheduleRepository.save(schedule);
    }

    @Override
    public Page<Schedule> listSchedule(Integer page, Integer limit, ScheduleQueryVo scheduleQueryVo) {
        Pageable pageable = PageRequest.of(page - 1, limit);
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo,schedule);
        ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Example<Schedule> example = Example.of(schedule, matcher);
        return scheduleRepository.findAll(example,pageable);
    }

    @Override
    public void removeSchedule(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if(schedule==null) {
            throw new YyghException(ResultCodeEnum.SCHEDULE_NO);
        }
        scheduleRepository.deleteById(schedule.getId());
    }
}
